using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Net;
using mojoPortal.Web;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using Resources;
using ud_Forum.Business;

namespace ud_Forum
{

    public partial class ForumPostEdit : NonCmsBasePage
	{
        
		private int moduleId = -1;
        private int forumId = -1;
        private int threadId = -1;
        private int postId = -1;
        private int pageId = -1;
        private int pageNumber = 1;
        private SiteUser theUser;
        private Forum forum;
        private Double timeOffset;
        private TimeZoneInfo timeZone;
        private bool isSubscribedToForum;
        private bool isSubscribedToThread;
        protected string allowedImageUrlRegexPattern = SecurityHelper.RegexAnyImageUrlPatern;
        //Gravatar public enum RatingType { G, PG, R, X }
        protected Gravatar.RatingType MaxAllowedGravatarRating = SiteUtils.GetMaxAllowedGravatarRating();
        protected bool allowGravatars;
        private bool disableAvatars = true;
        private bool useSpamBlockingForAnonymous = true;
        protected Hashtable moduleSettings;
        private bool isModerator;
        private bool includePostBodyInNotification;

        public double TimeOffset
        {
            get { return timeOffset; }
        }

        

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);

            
            
        }

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnUpdate.Click += btnUpdate_Click;
            //btnCancel.Click += new EventHandler(btnCancel_Click);
            btnDelete.Click += btnDelete_Click;

            SecurityHelper.DisableBrowserCache();
            

            if ((siteSettings != null) && (CurrentPage != null))
            {
                if ((SiteUtils.SslIsAvailable())
                    && ((siteSettings.UseSslOnAllPages) || (CurrentPage.RequireSsl))
                    )
                {
                    SiteUtils.ForceSsl();
                }
                else
                {
                    SiteUtils.ClearSsl();
                }

            }

            SiteUtils.SetupEditor(edMessage, AllowSkinOverride, this);

            
        }

        #endregion

        private void Page_Load(object sender, EventArgs e)
		{
            LoadSettings();



            if (!UserCanViewPage(moduleId, Forum.FeatureGuid))
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            if (forumId == -1)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            
            forum = new Forum(forumId);
                
            if (forum.ItemId == -1)
            {
                Response.Redirect(siteSettings.SiteRoot);
            }

            if (moduleId != forum.ModuleId)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;

            }

            if (!forum.AllowAnonymousPosts)
            {
                if (!Request.IsAuthenticated)
                {
                    SiteUtils.RedirectToLoginPage(this);
                    return;
                }

                pnlAntiSpam.Visible = false;
                captcha.Enabled = false;
                //pnlEdit.Controls.Remove(pnlAntiSpam);
            }
            else
            {
                if ((!useSpamBlockingForAnonymous) || (Request.IsAuthenticated))
                {
                    pnlAntiSpam.Visible = false;
                    captcha.Enabled = false;
                    //pnlEdit.Controls.Remove(pnlAntiSpam);
                }

            }
           
           
			
            SetupCss();
			PopulateLabels();

			if(!Page.IsPostBack)
			{
				PopulateControls();
                if ((Request.UrlReferrer != null) && (hdnReturnUrl.Value.Length == 0))
                {
                    hdnReturnUrl.Value = Request.UrlReferrer.ToString();
                    lnkCancel.NavigateUrl = Request.UrlReferrer.ToString();

                }
			}

            AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsForumSection", "forums");
			

		}

		private void PopulateControls()
		{
            ForumThread thread = null;
		    if(threadId == -1)
			{
				btnDelete.Visible = false;
				rptMessages.Visible = false;
                Title = SiteUtils.FormatPageTitle(siteSettings, CurrentPage.PageName + " - " + ForumResources.NewTopicLabel);
			}
			else
			{
			    
			    if(postId > -1)
				{
					thread = new ForumThread(threadId, postId);
                    if (isModerator
                        || ((theUser != null) && (theUser.UserId == thread.PostUserId))
                        )
                    {
                        txtSubject.Text = thread.PostSubject;
                        edMessage.Text = thread.PostMessage;
                    }
                    else
                    {
                        //user has no permission to edit this post
                        WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                        return;

                    }

                    if (isModerator)
                    {
                        divSortOrder.Visible = true;
                        txtSortOrder.Text = thread.PostSortOrder.ToInvariantString();
                    }
				}
				else
				{  
					thread = new ForumThread(threadId);
                    txtSubject.Text
                        = ResourceHelper.GetMessageTemplate(SiteUtils.GetDefaultCulture(), "ForumPostReplyPrefix.config") 
                        + thread.Subject;
                }

                if (thread.IsLocked && (!isModerator))
                {
                    WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                    return;
                }


                if ((forum != null) && (thread != null))
                {
                    Title = SiteUtils.FormatPageTitle(siteSettings, forum.Title + " - " + thread.Subject);
                }

                if (forumId == -1)
                {
                    forumId = thread.ForumId;
                }

                using(IDataReader reader = thread.GetPostsReverseSorted())
                {
                    rptMessages.DataSource = reader;
                    rptMessages.DataBind();
                    
                }
			}

            if (forum != null)
            {
                litForumPostLabel.Text = forum.Title;
                litForumDescription.Text = forum.Description;
                
            }

            if (postId == -1)
            {
                string hookupInputScript = "<script type=\"text/javascript\">"
                     + "document.getElementById('" + txtSubject.ClientID + "').focus();</script>";

                if (!Page.ClientScript.IsStartupScriptRegistered("finitscript"))
                {
                    Page.ClientScript.RegisterStartupScript(
                        typeof(Page),
                        "finitscript", hookupInputScript);
                }
            }

            chkNotifyOnReply.Checked = isSubscribedToThread;

            lnkPageCrumb.Text = CurrentPage.PageName;
            lnkPageCrumb.NavigateUrl = SiteUtils.GetCurrentPageUrl();
		    if (forum != null)
		    {
		        lnkForum.HRef = SiteRoot + "/Forums/ForumView.aspx?ItemID="
		                        + forum.ItemId.ToInvariantString()
		                        + "&amp;pageid=" + pageId.ToInvariantString()
		                        + "&amp;mid=" + forum.ModuleId.ToInvariantString();

		        lnkForum.InnerHtml = forum.Title;
		    }
		    if (thread != null) { lblThreadDescription.Text = Server.HtmlEncode(thread.Subject); }
		}


		private void btnDelete_Click(object sender, EventArgs e)
		{
			ForumThread thread = new ForumThread(threadId,postId);
            bool userCanEditPost = false;
            if (isModerator
                   || ((theUser != null) && (theUser.UserId == thread.PostUserId) && (thread.ForumId == forumId))
               )
              {
                  userCanEditPost = true;
              }

            if (!userCanEditPost)
            {
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                return;

            }

            thread.ContentChanged += thread_ContentChanged;
            
            

			if(thread.DeletePost(postId))
			{
                CurrentPage.UpdateLastModifiedTime();
               
                if (thread.PostUserId > -1)
                {
                    Forum.UpdateUserStats(thread.PostUserId);
                }

                SiteUtils.QueueIndexing();
			}

            if (hdnReturnUrl.Value.Length > 0)
            {
                WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
                return;
            }

            WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
		}


        private void btnUpdate_Click(object sender, EventArgs e)
		{
            if (forum == null) { forum = new Forum(forumId); }

            if (!forum.AllowAnonymousPosts)
            {
                captcha.Enabled = false;
                pnlAntiSpam.Visible = false;
               // pnlEdit.Controls.Remove(pnlAntiSpam);

                if (!Request.IsAuthenticated)
                {
                    SiteUtils.RedirectToAccessDeniedPage(this);
                    return;
                }
            }

			Page.Validate("Forum");
			if(!Page.IsValid)
			{
                PopulateControls();
                return;
            }
            if ((useSpamBlockingForAnonymous) && (pnlAntiSpam.Visible)&&(captcha.Enabled))
            {
                if (!captcha.IsValid)
                {
                    PopulateControls();
                    return;
                }
            }

            ForumThread thread;
            bool userIsAllowedToUpdateThisPost = false;
            if(threadId == -1)
            {
                //new thread
                thread = new ForumThread {ForumId = forumId};
            }
            else
            {

                if(postId > -1)
                {
                    thread = new ForumThread(threadId,postId);
                    if (isModerator || (theUser.UserId == thread.PostUserId))
                    {
                        userIsAllowedToUpdateThisPost = true;
                    }

                    if ((isModerator) && (divSortOrder.Visible))
                    {
                        int sort;
                        int.TryParse(txtSortOrder.Text, out sort);
                        thread.PostSortOrder = sort;
                    }

                }
                else
                {
                    thread = new ForumThread(threadId);
                }

                //existing thread but it does not belong to this forum
                if (forumId != thread.ForumId)
                {
                    SiteUtils.RedirectToAccessDeniedPage(this);
                    return;
                }

            }

            thread.ContentChanged += thread_ContentChanged;
            thread.PostSubject = txtSubject.Text;
            thread.PostMessage = edMessage.Text;

            SiteUser siteUser = null;
			
            if(Request.IsAuthenticated)
            {
                siteUser = SiteUtils.GetCurrentSiteUser();
                if (siteUser != null) 
                    thread.PostUserId = siteUser.UserId;
                if (chkSubscribeToForum.Checked)
                {
                    if (siteUser != null) forum.Subscribe(siteUser.UserId);
                }
                else
                {
                    thread.SubscribeUserToThread = chkNotifyOnReply.Checked;
                }
				
            }
            else
            {
                thread.PostUserId = -1; //guest
            }

            string threadViewUrl = SiteRoot + "/Forums/Thread.aspx?thread=" 
                                   + thread.ThreadId.ToInvariantString()
                                   + "&mid=" + moduleId.ToInvariantString()
                                   + "&pageid=" + pageId.ToInvariantString()
                                   + "&ItemID=" + forumId.ToInvariantString()
                                   + "&pagenumber=" + pageNumber.ToInvariantString();

            if((thread.PostId == -1)||(userIsAllowedToUpdateThisPost))
            {
                thread.Post();
                CurrentPage.UpdateLastModifiedTime();

                threadViewUrl = SiteRoot + "/Forums/Thread.aspx?thread="
                                + thread.ThreadId.ToInvariantString()
                                + "&mid=" + moduleId.ToInvariantString()
                                + "&pageid=" + pageId.ToInvariantString()
                                + "&ItemID=" + forumId.ToInvariantString()
                                + "&pagenumber=" + pageNumber.ToInvariantString()
                                + "#post" + thread.PostId.ToInvariantString();

                // Send notification to subscribers
                DataSet dsThreadSubscribers = thread.GetThreadSubscribers();

                ForumNotificationInfo notificationInfo = new ForumNotificationInfo();

                CultureInfo defaultCulture = SiteUtils.GetDefaultCulture();

                notificationInfo.SubjectTemplate
                    = ResourceHelper.GetMessageTemplate(defaultCulture, 
                                                        "ForumNotificationEmailSubject.config");

                if (includePostBodyInNotification)
                {
                    string postedBy = string.Empty;
                    if (siteUser != null)
                    {
                        string sigFormat = ResourceHelper.GetResourceString("ForumResources", "PostedByFormat", defaultCulture, true);
                        postedBy = string.Format(CultureInfo.InvariantCulture, sigFormat, siteUser.Name) + "\r\n\r\n";
                    }
                    notificationInfo.MessageBody = Server.HtmlDecode(SecurityHelper.RemoveMarkup(thread.PostMessage)) + "\r\n\r\n" + postedBy;
                }

                notificationInfo.BodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumNotificationEmail.config");
                notificationInfo.ForumOnlyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumNotificationEmail-ForumOnly.config");
                notificationInfo.ThreadOnlyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "ForumNotificationEmail-ThreadOnly.config");

                notificationInfo.FromEmail = siteSettings.DefaultEmailFromAddress;
                notificationInfo.SiteName = siteSettings.SiteName;
                notificationInfo.ModuleName = new Module(moduleId).ModuleTitle;
                notificationInfo.ForumName = new Forum(forumId).Title;
                notificationInfo.Subject = thread.PostSubject;
                notificationInfo.Subscribers = dsThreadSubscribers;
                notificationInfo.MessageLink = threadViewUrl;
                notificationInfo.UnsubscribeForumThreadLink = SiteRoot + "/Forums/UnsubscribeThread.aspx?threadid=" + thread.ThreadId;
                notificationInfo.UnsubscribeForumLink = SiteRoot + "/Forums/UnsubscribeForum.aspx?mid=" + moduleId + "&itemid=" + thread.ForumId;
                notificationInfo.SmtpSettings = SiteUtils.GetSmtpSettings();

                ThreadPool.QueueUserWorkItem(Notification.SendForumNotificationEmail, notificationInfo);
                    
                String cacheDependencyKey = "Module-" + moduleId.ToInvariantString();
                CacheHelper.TouchCacheDependencyFile(cacheDependencyKey);
                SiteUtils.QueueIndexing();
                   
            }

            //WebUtils.SetupRedirect(this, threadViewUrl);
            Response.Redirect(threadViewUrl);
		}

        void thread_ContentChanged(object sender, ContentChangedEventArgs e)
        {
            IndexBuilderProvider indexBuilder = IndexBuilderManager.Providers["ForumThreadIndexBuilderProvider"];
            if (indexBuilder != null)
            {
                indexBuilder.ContentChangedHandler(sender, e);
            }
        }

        protected int GetUserId(object obj)
        {
            if (obj == null) { return -1; }
            if (obj == DBNull.Value) { return -1; }
            return Convert.ToInt32(obj, CultureInfo.InvariantCulture);

        }

        protected string FormatDate(DateTime startDate)
        {
            if (timeZone != null)
            {
                return TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString();

            }

            return startDate.AddHours(TimeOffset).ToString();

        }

        public String GetAvatarUrl(String avatar)
        {
            if (allowGravatars) { return string.Empty; }
            if (disableAvatars) { return string.Empty; }

            if (string.IsNullOrEmpty(avatar))
            {
                avatar = "blank.gif";
            }
            return "<img  alt='' src='"
                + Page.ResolveUrl("~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/useravatars/" + avatar) + "' />";
        }

        private void PopulateLabels()
        {
            reqSubject.ErrorMessage = ForumResources.ForumEditSubjectRequiredHelp;
            lblThreadDescription.Text = ForumResources.NewTopicLabel;

            btnUpdate.Text = ForumResources.ForumPostEditUpdateButton;
            SiteUtils.SetButtonAccessKey(btnUpdate, ForumResources.ForumPostEditUpdateButtonAccessKey);

            UIHelper.DisableButtonAfterClick(
                btnUpdate,
                ForumResources.ButtonDisabledPleaseWait,
                Page.ClientScript.GetPostBackEventReference(btnUpdate, string.Empty)
                );

            lnkCancel.Text = ForumResources.ForumPostEditCancelButton;
            
            btnDelete.Text = ForumResources.ForumPostEditDeleteButton;
            SiteUtils.SetButtonAccessKey(btnDelete, ForumResources.ForumEditDeleteButtonAccessKey);
            UIHelper.AddConfirmationDialog(btnDelete, ForumResources.ForumDeletePostWarning);

            if (postId == -1)
            {
                btnDelete.Visible = false;
            }

            if (!Request.IsAuthenticated) pnlNotify.Visible = false;
            if (isSubscribedToForum) pnlNotify.Visible = false;

            if (forumId == -1) pnlEdit.Visible = false;
        }


        private void SetupCss()
        { 
            // older skins have this
            if (Page.Master != null)
            {
                StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
                if (stylesheet != null)
                {
                    if (stylesheet.FindControl("forumcss") == null)
                    {
                        Literal cssLink = new Literal
                                              {
                                                  ID = "forumcss",
                                                  Text = @"<link href='"
                                                         + SiteUtils.GetSkinBaseUrl()
                                                         +
                                                         @"forummodule.css' type='text/css' rel='stylesheet' media='screen' />"
                                              };

                        stylesheet.Controls.Add(cssLink);
                    }
                }
            }
        }


	    private void LoadSettings()
        {
            WebUtils.GetApplicationRoot();

            pageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            forumId = WebUtils.ParseInt32FromQueryString("forumid", -1);
            threadId = WebUtils.ParseInt32FromQueryString("thread", -1);
            postId = WebUtils.ParseInt32FromQueryString("postid", -1);
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", 1);
            lnkCancel.NavigateUrl = SiteUtils.GetCurrentPageUrl();
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();

            isModerator = UserCanEditModule(moduleId);

            switch (siteSettings.AvatarSystem)
            {
                case "gravatar":
                    allowGravatars = true;
                    disableAvatars = true;
                    break;

                case "internal":
                    allowGravatars = false;
                    disableAvatars = false;
                    break;

                default:
                    allowGravatars = false;
                    disableAvatars = true;
                    break;

            }

            if (Request.IsAuthenticated)
            {
                theUser = SiteUtils.GetCurrentSiteUser();
                if (forumId > -1)
                {
                    isSubscribedToForum = Forum.IsSubscribed(forumId, theUser.UserId);
                }
                if (threadId > -1)
                {
                    isSubscribedToThread = ForumThread.IsSubscribed(threadId, theUser.UserId);
                }
            }

            if (isModerator)
            {
                edMessage.WebEditor.ToolBar = ToolBar.FullWithTemplates;
            }
            else if ((Request.IsAuthenticated)&&(WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles)))
            {
                edMessage.WebEditor.ToolBar = ToolBar.ForumWithImages;
            }
            else
            {
                edMessage.WebEditor.ToolBar = ToolBar.Forum;
            }

            edMessage.WebEditor.SetFocusOnStart = true;
            edMessage.WebEditor.Height = Unit.Parse("350px");

            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);

            useSpamBlockingForAnonymous = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "ForumEnableAntiSpamSetting", useSpamBlockingForAnonymous);

            includePostBodyInNotification = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "IncludePostBodyInNotificationEmail", includePostBodyInNotification);

           

            if (useSpamBlockingForAnonymous)
            {
                captcha.ProviderName = siteSettings.CaptchaProvider;
                captcha.Captcha.ControlID = "captcha" + moduleId.ToString(CultureInfo.InvariantCulture);
                captcha.RecaptchaPrivateKey = siteSettings.RecaptchaPrivateKey;
                captcha.RecaptchaPublicKey = siteSettings.RecaptchaPublicKey;
            }


            AddClassToBody("editforumpost");

        }

	}
}
